<template>
  <div class="card" style="height: 100%">
    <div class="header-row">
      <el-cascader
        v-model="activeTab"
        :options="cascaderOptions"
        :props="cascaderProps"
        placeholder="请选择分类和标签"
        style="width: calc(100% - 240px)"
        @change="handleCascaderChange"
        @expand-change="handleExpandChange"
      >
        <template #default="{ node, data }">
          <span>{{ data.label }}</span>
          <span v-if="node.isLeaf" class="action-buttons">
            <el-button size="small" link @click.stop="editTab(data)">
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button size="small" link @click.stop="removeTab(data)">
              <el-icon><DeleteFilled /></el-icon>
            </el-button>
          </span>
        </template>
      </el-cascader>
      <el-button size="small" @click="showAddCategoryDialog" style="margin: 0 10px">
        <el-icon><CirclePlusFilled /></el-icon>
        添加分类
      </el-button>
      <el-button size="small" @click="showAddTabDialog" :disabled="!currentCategory" style="margin: 0 10px">
        <el-icon><CirclePlusFilled /></el-icon>
        添加标签
      </el-button>
    </div>
    <ShareExcel :name="excelName" />

    <!-- 添加/编辑标签的 Dialog -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="30%" :close-on-click-modal="false">
      <el-form :model="currentTab" label-width="60px">
        <el-form-item label="名称" required>
          <el-input v-model="currentTab.label" placeholder="请输入标签名称"></el-input>
        </el-form-item>
        <el-form-item label="链接" required>
          <el-input v-model="currentTab.link" placeholder="请输入链接"></el-input>
        </el-form-item>
        <el-form-item label="分类" required>
          <el-select v-model="currentTab.category" placeholder="请选择分类">
            <el-option v-for="category in categories" :key="category" :label="category" :value="category"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitDialog">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加新分类的 Dialog -->
    <el-dialog title="添加新分类" v-model="categoryDialogVisible" width="30%" :close-on-click-modal="false">
      <el-form :v-model="newCategory" label-width="60px">
        <el-form-item label="分类" required>
          <el-input v-model="newCategory" placeholder="请输入新分类名称"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="categoryDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitNewCategory">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { CirclePlusFilled, DeleteFilled, Edit } from "@element-plus/icons-vue";
import ShareExcel from "@/components/ShareExcel/index.vue";
import { GetTabData, addTabData, deleteTabData } from "@/api/modules/upload";

interface TabItem {
  label: string;
  value: string;
  link: string;
  category: string;
}
const props = defineProps({
  name: {
    type: String,
    required: true
  }
});
const params = { path: props.name };
const tabItems = ref<TabItem[]>([]);

const cascaderOptions = computed(() => {
  const groups: { [key: string]: TabItem[] } = {};
  tabItems.value.forEach(item => {
    if (!groups[item.category]) {
      groups[item.category] = [];
    }
    groups[item.category].push(item);
  });
  return Object.keys(groups).map(key => ({
    value: key,
    label: key,
    children: groups[key].map(item => ({
      value: item.value,
      label: item.label,
      link: item.link,
      category: item.category
    }))
  }));
});
const updateTabItems = async () => {
  const res = await GetTabData(params);
  tabItems.value = res.data as TabItem[];
  await nextTick(); // 等待 DOM 更新
  setDefaultActiveTab();
};

const setDefaultActiveTab = () => {
  if (tabItems.value.length > 0) {
    const firstCategory = tabItems.value[0].category;
    const firstItem = tabItems.value[0];
    activeTab.value = [firstCategory, firstItem.value];
    currentCategory.value = firstCategory;
  } else {
    activeTab.value = [];
  }
};

onMounted(async () => {
  await updateTabItems();
});

const categories = computed(() => {
  return Array.from(new Set(tabItems.value.map(item => item.category)));
});

const activeTab = ref<string[]>([]);
const dialogVisible = ref(false);
const categoryDialogVisible = ref(false);
const dialogTitle = ref("");
const currentTab = ref<TabItem>({ label: "", value: "", link: "", category: "" });
const isEditing = ref(false);
const isAddingTab = ref(false);
const newCategory = ref<string>("");
const currentCategory = ref("");

const handleExpandChange = (expandedKeys: string[]) => {
  currentCategory.value = expandedKeys[expandedKeys.length - 1] || "";
};

const cascaderProps = {
  expandTrigger: "hover" as const,
  checkStrictly: false
};

const excelName = computed(() => ({
  path: `${params.path}.${activeTab.value.join(".")}`
}));

const handleCascaderChange = (value: string[]) => {
  currentCategory.value = value[0] || "";
};

const showAddCategoryDialog = () => {
  newCategory.value = "";
  categoryDialogVisible.value = true;
};

const submitNewCategory = async () => {
  if (!newCategory.value) {
    ElMessage.warning("请输入分类名称");
    return;
  }
  if (cascaderOptions.value.some(group => group.label === newCategory.value)) {
    ElMessage.warning("该分类已存在");
    return;
  }
  try {
    await addTabData({ path: params.path + "." + newCategory.value });
    await updateTabItems(); // 更新 tabItems
    categoryDialogVisible.value = false;
    ElMessage.success(`新分类 "${newCategory.value}" 已添加`);
  } catch (error) {
    ElMessage.error("添加分类失败");
  }
};

const showAddTabDialog = () => {
  if (!currentCategory.value) {
    ElMessage.warning("请先选择一个分类");
    return;
  }
  dialogTitle.value = "添加新标签";
  currentTab.value = { label: "", value: "", link: "", category: currentCategory.value };
  isEditing.value = false;
  isAddingTab.value = true;
  dialogVisible.value = true;
};

const editTab = (data: TabItem) => {
  dialogTitle.value = "编辑标签";
  currentTab.value = {
    label: data.label,
    value: data.value,
    link: data.value, // 确保这里使用 link 而不是 value
    category: data.category
  };
  isEditing.value = true;
  isAddingTab.value = false;
  dialogVisible.value = true;
};

const submitDialog = async () => {
  if (!currentTab.value.label || !currentTab.value.link || !currentTab.value.category) {
    ElMessage.warning("请填写所有必填项");
    return;
  }

  try {
    if (isEditing.value) {
      await addTabData({
        path: params.path + "." + currentTab.value.category,
        label: currentTab.value.label,
        value: currentTab.value.link
      });
    } else {
      const newTab = { ...currentTab.value, value: currentTab.value.label };
      await addTabData({
        path: params.path + "." + newTab.category,
        label: newTab.label,
        value: newTab.link
      });
      activeTab.value = [newTab.category, newTab.value];
    }

    await updateTabItems(); // 更新 tabItems
    dialogVisible.value = false;
    ElMessage.success(`标签 "${currentTab.value.label}" 已${isEditing.value ? "更新" : "添加"}`);
  } catch (error) {
    ElMessage.error(`${isEditing.value ? "更新" : "添加"}标签失败`);
  }
};

const removeTab = async (data: TabItem) => {
  try {
    await ElMessageBox.confirm(`确定要删除标签 "${data.label}" 吗？`, "删除标签", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    // 这里应该调用删除标签的 API
    await deleteTabData({ path: params.path + "." + data.category, label: data.label });

    await updateTabItems(); // 更新 tabItems
    if (activeTab.value[1] === data.value) {
      activeTab.value = [];
    }
    ElMessage({
      type: "success",
      message: `标签 "${data.label}" 已删除`
    });
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除标签失败");
    }
  }
};
</script>

<style scoped>
.header-row {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.button-row {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  margin-bottom: 20px;
}
.action-buttons {
  position: relative;
}
</style>
